var UUID = require('../../utils/Math.uuid.js');
var KL = require('../../template/zakl/kouling.js');
var ordertype;
var app = getApp();
var dateArr, dateChArr, timeArr, dateWeekArr, timeChArr;
var mid, fid, stationId;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tipsOK: '1',
    balanceUsed: '0'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options.type);
    ordertype = '';
    if (options.type) {
      ordertype = options.type;
    }
    this.setData({
      ordertype: ordertype,
      usernotes: ''
    });

    KL.init(this);
    var goods = [];
    if (options.orderinfo) {
      if (ordertype == 'cake') {
        var cakedata = JSON.parse(decodeURIComponent(options.orderinfo));
        goods = cakedata.goodslist;
        for (var i = 0; i < goods.length; i++) {
          goods[i].boardcard = 'Happy Birthday';
        }
        mid = cakedata.mid;
        fid = cakedata.fid;
        stationId = cakedata.stationId;
        this.setData({
          partsnotes: [
            '每套标配餐具：一个餐盘、一把餐勺',
            '赠送一只工艺蜡烛',
            '若不填写巧克力牌则为默认(限8字以内)'
          ]
        });
      }
      else {
        goods = JSON.parse(decodeURIComponent(options.orderinfo));
      }
    };
    this.setData({
      goods: goods,
      codeval: '',
      codeStatus: 0,
      codeprice: 0,
      balanceStatus: 0,
      pointStatus: 1,
      computeId: null,
      couponName: '',
      cardNo: null,
      cardPwd: null
    });

    dateArr = [];
    dateChArr = [];
    timeArr = [];
    if (options.address) {
      var address = JSON.parse(decodeURIComponent(options.address));
      this.setData({
        address: address
      });
      this.loadSendTime();
      this.loadKLAndPrice();
    }
    else {
      if (app.globalData.address) {
        var address = app.globalData.address;
        this.setData({
          address: address
        });
        this.loadSendTime();
        this.loadKLAndPrice();
      }
      else {
        wx.switchTab({
          url: '../index/index',
        });
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.selectAddress.status == 1) {
      var address = app.globalData.selectAddress.value;
      app.globalData.selectAddress.status = -1;
      app.globalData.selectAddress.value = null;
      this.setData({
        address: address
      });
    }

    if (app.globalData.tempCoupon){
      this.setData({
        computeId: app.globalData.tempCoupon.id,
        couponName: app.globalData.tempCoupon.name
      });
      app.globalData.tempCoupon = null;
      this.loadKLAndPrice();
    }

    if (app.globalData.tempCashCard){
      this.setData({
        cardNo: app.globalData.tempCashCard.cardNo,
        cardPwd: app.globalData.tempCashCard.cardPwd
      });
      app.globalData.tempCashCard = null;
      this.loadKLAndPrice();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  agreeMatter: function () {
    if (this.data.tipsOK == '1') {
      this.setData({
        tipsOK: '0'
      });
    }
    else {
      this.setData({
        tipsOK: '1'
      });
    }
  },
  balanceUsedAction: function () {
    if (this.data.balanceUsed == '1') {
      this.setData({
        balanceUsed: '0',
        balanceStatus: 0,
      });
    }
    else {
      this.setData({
        balanceUsed: '1',
        balanceStatus: 1
      });
    }
    this.loadKLAndPrice();
  },
  maidianChange: function (e) {
    console.log(e.detail.value);
    var pointstatus = 0;
    if (e.detail.value == true) {
      pointstatus = 1
    }
    this.setData({
      pointStatus: pointstatus
    });
    this.loadKLAndPrice();
  },
  chooseCoupon: function () {
    var couponlist;
    if (ordertype == 'cake') {
      couponlist = this.data.extrainfo.PROMOTION;
    }
    else {
      couponlist = JSON.stringify(this.data.extrainfo.PROMOTION);
    }
    wx.navigateTo({
      url: '../my/coupon/choose?coupon=' + couponlist,
    });
  },
  useCashCard:function(){
    wx.navigateTo({
      url: '../my/cashcard/cashcard',
    });
  },
  //----------------------------------------------------------------
  loadSendTime: function (senddate = '') {
    var url;
    var property;
    var cityid = app.globalData.address.CITYID;
    if (ordertype == 'cake') {
      url = '/yuanmai_we/mcake/delivery/time/get';
      var sku_arr = [];
      for (var i = 0; i < this.data.goods.length; i++) {
        sku_arr.push(this.data.goods[i].sku);
      }
      var skustr = sku_arr.join(',');
      property = { "cityId": cityid, "stationId": stationId, "sku": skustr, "fid": fid, "mid": mid, "date": senddate };
    }
    else {
      url = '/yuanmai_we/product/deliverytime/list';
      var curdate = app.formatDateTime((new Date()).getTime() / 1000);
      var storeid = this.data.goods[0].stationId;
      var location = app.globalData.address.LOCATION;
      console.log(curdate, cityid, storeid);
      var products = [];
      for (var i = 0; i < this.data.goods.length; i++) {
        var goodsinfo = {
          id: this.data.goods[i].ID,
          STOCK: this.data.goods[i].STOCK
        }
        products.push(goodsinfo);
      }
      var property = {
        "DTS": "DRHR",
        "date": curdate,
        "ORDERSTARTDAY": "TODAY",
        "CITYID": cityid,
        "ORDERSOURCE": "NORMAL",
        "productList": products,
        "location": location,
        "STOREID": storeid
      }
    }
    var params = {
      datas: JSON.stringify(property),
      __zaofans: true
    }
    app.loadDataFromServer(url, this.loadSendTimeCallBack, params, 'post');
  },
  loadSendTimeCallBack: function (res) {
    console.log(res);
    if (ordertype == 'bread') {
      this.dealResForBread(res);
    }
    else {
      this.dealResForCake(res);
    }
  },
  dealResForBread: function (res) {
    dateArr = [];
    dateChArr = [];
    timeArr = [];
    dateWeekArr = [];
    timeChArr = [];
    for (var i = 0; i < res.length; i++) {
      var datetime = res[i].date;
      var chstr = '';
      if (res[i].dayOfWeek == null || res[i].dayOfWeek == undefined) {
        chstr = '45分钟极速送达';
      }
      else {
        chstr = res[i].DR + ' ' + res[i].dayOfWeek;
      }
      if (dateWeekArr.indexOf(chstr) >= 0) {
        timeArr[timeArr.length - 1].push(res[i].HR);
        timeChArr[timeChArr.length - 1].push(res[i].HR);
      }
      else {
        if (res[i].dayOfWeek == null || res[i].dayOfWeek == undefined) {
          dateWeekArr.push('45分钟极速送达');
          timeChArr.push(['']);
        }
        else {
          var str = res[i].DR + ' ' + res[i].dayOfWeek;
          dateWeekArr.push(str);
          timeChArr.push([res[i].HR]);
        };
        timeArr.push([res[i].HR]);
        dateArr.push(datetime);
        dateChArr.push(res[i].DR);
      }
    }
    var dateTimeSets = [
      dateWeekArr,
      timeChArr[0]
    ];
    this.setData({
      timeIndex: [0, 0],
      dateTimeSets: dateTimeSets
    });
  },
  dealResForCake: function (res) {
    if (res.data.dispDate) {
      dateArr = [];
      dateChArr = [];
      for (var i = 0; i < res.data.dispDate.length; i++) {
        dateArr.push(res.data.dispDate[i].date);
        dateChArr.push(res.data.dispDate[i].date + ' ' + res.data.dispDate[i].week);
      }
    }
    if (res.data.dispTime) {
      timeArr = [];
      for (var i = 0; i < res.data.dispTime.list.length; i++) {
        for (var j = 0; j < res.data.dispTime.list[i].list.length; j++) {
          var timestr = res.data.dispTime.list[i].hour + ':' + res.data.dispTime.list[i].list[j].min;
          timeArr.push(timestr);
        }
      }
    }
    var dateTimeSets = [
      dateChArr,
      timeArr
    ];
    var timeIndex = [0, 0];
    if (this.data.timeIndex) {
      timeIndex = this.data.timeIndex;
      timeIndex[1] = 0;
    }
    this.setData({
      timeIndex: timeIndex,
      dateTimeSets: dateTimeSets
    });
  },
  // ----------------------- PRICE deal--------------------------------
  loadKLAndPrice: function () {
    var products = [];
    var totalcount = 0;
    for (var i = 0; i < this.data.goods.length; i++) {
      var num;
      if (this.data.goods[i].COUNT) {
        num = this.data.goods[i].COUNT;
      }
      else {
        num = this.data.goods[i].num;
      }
      var productinfo = {
        id: this.data.goods[i].ID,
        num: num
      };
      products.push(productinfo);
      totalcount += parseInt(num);
    }
    this.setData({
      totalcount: totalcount
    });
    var property;
    var params;
    var url;
    if (ordertype == 'cake') {
      url = '/yuanmai_we/mcake/order/compute';
      var address = {
        "location": this.data.address.LOCATION,
        "city": this.data.address.CITYNAME,
        "county": this.data.address.COUNTYNAME,
        "address": this.data.address.ADDRESS,
        "hasAddress": true
      };
      property = {
        "pointStatusBB": true,
        "pointStatus": this.data.pointStatus,
        "codeStatus": 0,
        "computeId": this.data.computeId,
        "codeValue": null,
        "showPromotion": false,
        "balanceStatus": this.data.balanceStatus,
        "balanceStatusBB": false,
        "cardNo": this.data.cardNo,
        "cardPwd": this.data.cardPwd,
        "meals": products
      };
      params = {
        datas: JSON.stringify(property),
        address: JSON.stringify(address),
        __zaofans: true
      };
    }
    else {
      url = '/yuanmai_we/orders/orderFormOrder/compute';
      var property = {
        "pointStatusBB": true,
        "pointStatus": this.data.pointStatus,
        "codeStatus": this.data.codeStatus,
        "computeId": this.data.computeId,
        "codeValue": this.data.codeval,
        "showPromotion": false,
        "balanceStatus": this.data.balanceStatus,
        "meals": products,
        "orderSource": "NORMAL",
        "balanceStatusBB": true
      };
      var params = {
        datas: JSON.stringify(property),
        __zaofans: true
      };
    }
    wx.showLoading({
      title: '',
    });
    app.loadDataFromServer(url, this.loadKLAndPriceCallBack, params, 'post', true);
  },
  loadKLAndPriceCallBack: function (res) {
    wx.hideLoading();
    if (ordertype == 'bread') {
      if (res.RESULT == 'SUCCESS') {
        res.PAYTATOL = app.keepTwoDecimalFull(res.PAYTATOL);
        res.DELIVERPAY = app.keepTwoDecimalFull(res.DELIVERPAY);
        res.TOTALPRICE = app.keepTwoDecimalFull(res.TOTALPRICE);
        if (res.PROMOTION) {
          res.couponNum = res.PROMOTION.AVAILABLEPROMOTIONS.length;
        }
        else{
          res.couponNum = 0;
        }
        var status;
        if (parseFloat(res.CODEVALUE) > 0) {
          status = 1;
        }
        else {
          status = 0;
        }
        this.setData({
          codeStatus: status,
          codeprice: res.CODEVALUE,
          extrainfo: res
        });
      }
      else {
        wx.showToast({
          title: res.MSG,
          icon: 'none'
        });
        if (this.data.extrainfo.CODEVALUE > 0){
          this.setData({
            computeId: null,
            couponName: ''
          });
        }
        else{
          this.setData({
            codeStatus: 0,
            codeprice: 0
          });
        }
        if (this.data.extrainfo.PROMOTIONVALUE > 0){
          this.setData({
            codeStatus: 0,
            codeprice: 0
          });
        }
        else{
          this.setData({
            computeId: null,
            couponName: ''
          });
        }
      }
    }
    else {
      if (res.success == true){
        res = res.data;
        res.PAYTATOL = app.keepTwoDecimalFull(res.payTotal);
        res.TOTALPRICE = app.keepTwoDecimalFull(res.totalPrice);
        res.DELIVERPAY = app.keepTwoDecimalFull(0);
        res.BALANCE = res.balance;
        res.PAYBALANCE = res.payBalance;
        if (res.PROMOTION){
          var coupons = JSON.parse(res.PROMOTION);
          res.couponNum = coupons.AVAILABLEPROMOTIONS.length;
        }
        else{
          res.couponNum = 0;
        }
        if (!res.cashCardValue) {
          res.cashCardValue = 0;
        }
        this.setData({
          extrainfo: res
        });
      }
      else{
        if (this.data.extrainfo.cashCardValue <= 0){
          this.setData({
            cardNo: null,
            cardPwd: null
          });
        }
      }
    }
  },
  //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  bindDateTimeColumnChange: function (e) {
    var timeIndex = this.data.timeIndex;
    timeIndex[e.detail.column] = e.detail.value;
    if (e.detail.column == 0) {
      if (ordertype == 'bread') {
        var dateTimeSets = this.data.dateTimeSets;
        dateTimeSets[1] = timeChArr[e.detail.value];
        timeIndex[1] = 0;
        this.setData({
          dateTimeSets: dateTimeSets
        });
      }
      else {
        var target_date = dateArr[e.detail.value];
        this.loadSendTime(target_date);
      }
    }
    this.setData({
      timeIndex: timeIndex
    });
  },
  changeAddr: function () {
    wx.showModal({
      title: '',
      content: '切换地址可能导致购物车中部分商品无效，是否继续？',
      confirmColor: '#a08257',
      confirmText: '是',
      cancelText: '否',
      success: function (res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '../my/address/address?type=select',
          });
        }
      }
    });
  },
  cardInput: function (e) {
    var boardcard = e.detail.value;
    var index = e.currentTarget.dataset.cakeindex;
    var goods = this.data.goods;
    goods[index].boardcard = boardcard;
    this.setData({
      goods: goods
    });
  },
  notesInput: function (e) {
    this.setData({
      usernotes: e.detail.value
    });
  },
  payOrder: function () {
    if (this.data.tipsOK != '1') {
      wx.showToast({
        title: '请同意面包收货协议',
        icon: 'none',
      });
      return;
    }
    if (ordertype == 'bread') {
      this.breadPayOrder();
    }
    else {
      this.cakePayOrder();
    }
  },
  // -----------------------------------BREAD PAY----------------------------------------
  breadPayOrder: function () {

    var products = [];
    var temp_products = [];
    for (var i = 0; i < this.data.goods.length; i++) {
      var productinfo = {
        MEALID: this.data.goods[i].ID,
        COUNT: this.data.goods[i].COUNT
      };
      var tempro = {
        id: this.data.goods[i].ID,
        num: this.data.goods[i].COUNT
      }
      products.push(productinfo);
      temp_products.push(tempro);
    }
    var uuid = UUID.uuidFast();
    var datas = {
      "uuid": uuid,//用户的openid
      "DISPTYPE": "0",//配送方式，固定0
      "NOTIFYTIME": "8:00-9:00",//提醒时间，固定
      "CITY": this.data.address.CITYID,
      "ACTIVITYTRIGGER": "0",//固定值
      "STORENAME": "",//门店名称，固定值
      "POINTNAME": "0",//积分名称
      "CODENAME": this.data.codeval,//优惠码名称
      "STOREID": this.data.goods[0].stationId,//门店ID
      "ORDERSTARTDAY": "TODAY",//固定
      "PRODUCTSCOUNT": this.data.totalcount,//数量
      "LOCATION": this.data.address.LOCATION,
      "CITYNAME": this.data.address.CITYNAME,
      "CITYID": this.data.address.CITYID,
      "RECEIVERMOBILE": this.data.address.RECEIVERMOBILE,
      "TOWNNAME": this.data.address.TOWNNAME,
      "RECEIVERNAME": this.data.address.RECEIVERNAME,
      "ISDEFAULT": this.data.address.ISDEFAULT,
      "TOWNID": this.data.address.TOWNID,
      "PROVINCENAME": this.data.address.PROVINCENAME,
      "COUNTYNAME": this.data.address.COUNTYNAME,
      "ADDRESS": this.data.address.ADDRESS,
      "LABEL": this.data.address.LABEL,
      "PROVINCEID": this.data.address.PROVINCEID,
      "COUNTYID": this.data.address.COUNTYID,
      "DISPTIME": timeArr[this.data.timeIndex[0]][this.data.timeIndex[1]],
      "DISP_DATE_ALIAS": dateChArr[this.data.timeIndex[0]],
      "ORDERS": [{
        "DISPDATE": dateArr[this.data.timeIndex[0]],
        "BIRTHDAYCARD": "HappyBirthday",
        "MEALS": products
      }],
      "TOTALPRICE": this.data.extrainfo.TOTALPRICE,//总体价格
      "DISPCOST": this.data.extrainfo.DELIVERPAY,//配送费用
      "TOPAY": this.data.extrainfo.PAYTATOL,//应付款
      "DISCOUNT": this.data.extrainfo.DISCOUNT,//优惠额
      "CODEVALUE": this.data.codeprice,//优惠码抵扣金额
      "DELIVERPAY": this.data.extrainfo.DELIVERPAY,//配送费用
      "PAYBALANCE": this.data.extrainfo.PAYBALANCE,//已使用原麦余额
      "freeSecret": this.data.extrainfo.freeSecret,//是否开启了免密支付
      "PAYTATOL": this.data.extrainfo.PAYTATOL,//应付款
      "DELIVERDESC": this.data.extrainfo.DELIVERDESC,
      "RESULT": this.data.extrainfo.RESULT,
      "BALANCE": this.data.extrainfo.BALANCE,

      "DISTYPE": "IMMEDIATE",//配送类型
      "WEIXIN": this.data.extrainfo.PAYTATOL,//微信支付金额
      "PAYAMOUNT": this.data.extrainfo.PAYTATOL,
      "PROMOTIONINFO": [],//优惠券信息描述
      "usedResource": {
        "pointStatus": this.data.pointStatus,//0不使用积分,1选择使用积分
        "codeStatus": this.data.codeStatus,//是否使用优惠码
        "computeId": this.data.computeId,//选择卡券的唯一id
        "codeValue": this.data.codeval,//优惠码
        "showPromotion": false,
        "balanceStatus": this.data.balanceStatus,
        "meals": temp_products,
        "orderSource": "NORMAL"
      },//用户资产信息
      "MENUTYPE": "NORMAL"
    };
    var url = '/yuanmai_we/orders/orderform/create';
    var params = {
      datas: JSON.stringify(datas),
      __zaofans: true
    }
    app.appShowLoading(60000);
    app.loadDataFromServer(url, this.payOrderCallBack, params, 'post', true);
  },
  payOrderCallBack: function (res) {
    wx.hideToast();
    console.log(res);
    if (res.errorCode) {
      wx.showToast({
        title: res.error,
        icon: 'none'
      });
    }
    else {
      if (res.payInfo.type == 'paysuccess') {
        wx.showToast({
          title: '下单成功',
          duration: 1000
        });
        var delayid = setTimeout(function () {
          clearTimeout(delayid);
          wx.redirectTo({
            url: '../my/order/order?ordertype=3',
          });
        }, 1000);
      }
      else {
        var order = encodeURIComponent(JSON.stringify(res));
        wx.redirectTo({
          url: '../pay/pay?entry=neworder&order=' + order,
        });
      }
    }
  },
  //----------------------CAKE PAY----------------------------------------
  cakePayOrder: function () {
    var products = [];
    for (var i = 0; i < this.data.goods.length; i++) {
      var productinfo = {};
      productinfo.id = this.data.goods[i].ID;
      productinfo.num = this.data.goods[i].num;
      productinfo.remark = this.data.goods[i].boardcard;
      productinfo.image = this.data.goods[i].image;
      products.push(productinfo);
    }
    var useResource = {
      "pointStatusBB": true,
      "pointStatus": this.data.pointStatus,
      "codeStatus": 0,
      "computeId": this.data.computeId,
      "codeValue": null,
      "showPromotion": false,
      "balanceStatus": this.data.balanceStatus,
      "balanceStatusBB": true,
      "cardNo": this.data.cardNo,
      "cardPwd": this.data.cardPwd,
      "meals": products
    }
    var disptime = timeArr[this.data.timeIndex[1]] + '-' + timeArr[this.data.timeIndex[1]];
    var dispdate = dateArr[this.data.timeIndex[0]];
    var orderInfo = {
      "location": this.data.address.LOCATION,
      "cityName": this.data.address.CITYNAME,
      "cityId": this.data.address.CITYID,
      "receiverMobile": this.data.address.RECEIVERMOBILE,
      "receiverName": this.data.address.RECEIVERNAME,
      "countyName": this.data.address.COUNTYNAME,
      "address": this.data.address.ADDRESS,
      "countyId": this.data.address.COUNTYID,
      "dispTime": disptime,
      "dispDate": dispdate,
      "remark": this.data.usernotes,
      "stationId": stationId
    }
    var params = {
      useResource: JSON.stringify(useResource),
      orderInfo: JSON.stringify(orderInfo),
      __zaofans: true
    }
    wx.showLoading({
      title: '',
    });
    var url = '/yuanmai_we/mcake/order/create';
    app.loadDataFromServer(url, this.cakePayOrderCallBack, params, 'post', true);
  },
  cakePayOrderCallBack: function (res) {
    console.log(res);
    wx.hideLoading();
    if (res.success == true) {
      if (res.data.payInfo.type == 'paysuccess') {
        wx.showToast({
          title: '下单成功',
          duration: 1000
        });
        var delayid = setTimeout(function () {
          clearTimeout(delayid);
          wx.redirectTo({
            url: '../my/order/order?ordertype=3',
          });
        }, 1000);
      }
      else {
        var cake = encodeURIComponent(JSON.stringify(this.data.goods));
        var payinfo = encodeURIComponent(JSON.stringify(res.data.payInfo));
        wx.redirectTo({
          url: '../pay/pay?entry=neworder&cake=' + cake + '&payinfo=' + payinfo,
        });
      }
    }
    else {
      wx.showToast({
        title: '订单创建失败',
        icon: 'none'
      });
    }
  },
  //-------------------------输入 口令 ------------------------------------------------------
  inputKL: function (e) {
    var code = e.detail.value;
    this.setData({
      codeval: code,
    });
  },
  useKL: function () {
    if (this.data.codeval == null || this.data.codeval == undefined || this.data.codeval == '') {
      return;
    }
    this.setData({
      codeStatus: 1
    });
    this.loadKLAndPrice();
  },
  // ---------kou ling----------
  showKL: KL.check,
  closeKL: KL.close
})